/**
 * 模拟 P2P 节点服务器
 * 用于开发和测试
 */

const express = require('express');
const cors = require('cors');
const crypto = require('crypto');

const app = express();
const PORT = process.env.PORT || 3000;

// 模拟文件数据
const mockFiles = new Map();

// 生成模拟文件
function generateMockFile(filename, sizeMB = 10) {
  const totalSize = sizeMB * 1024 * 1024;
  const shardSize = 100 * 1024; // 100KB per shard
  const shardCount = Math.ceil(totalSize / shardSize);
  
  const shards = [];
  for (let i = 0; i < shardCount; i++) {
    const size = i === shardCount - 1 ? totalSize - i * shardSize : shardSize;
    const buffer = crypto.randomBytes(size);
    shards.push(buffer);
  }
  
  mockFiles.set(filename, {
    totalSize,
    shardSize,
    shards,
    shardCount
  });
  
  return { totalSize, shardCount };
}

// 初始化示例文件
generateMockFile('example.zip', 5);
generateMockFile('test.pdf', 2);
generateMockFile('video.mp4', 20);

app.use(cors());

// 获取文件元数据
app.get('/metadata', (req, res) => {
  const { file } = req.query;
  
  if (!file) {
    return res.status(400).json({ error: '缺少 file 参数' });
  }
  
  const fileData = mockFiles.get(file);
  
  if (!fileData) {
    // 自动生成新文件
    const { totalSize, shardCount } = generateMockFile(file, 5);
    const fileData = mockFiles.get(file);
    
    return res.json({
      totalSize: fileData.totalSize,
      shardSize: fileData.shardSize,
      shards: Array(fileData.shardCount).fill(null).map((_, i) => [i % 3]) // 简化的分片分布
    });
  }
  
  res.json({
    totalSize: fileData.totalSize,
    shardSize: fileData.shardSize,
    shards: Array(fileData.shardCount).fill(null).map((_, i) => [i % 3])
  });
});

// 获取分片
app.get('/shard', (req, res) => {
  const { file, index } = req.query;
  
  if (!file || index === undefined) {
    return res.status(400).json({ error: '缺少参数' });
  }
  
  const fileData = mockFiles.get(file);
  
  if (!fileData) {
    return res.status(404).json({ error: '文件不存在' });
  }
  
  const shardIndex = parseInt(index);
  
  if (shardIndex < 0 || shardIndex >= fileData.shards.length) {
    return res.status(404).json({ error: '分片索引无效' });
  }
  
  // 模拟网络延迟和不稳定性
  const delay = Math.random() * 100 + 50; // 50-150ms
  const shouldFail = Math.random() < 0.1; // 10% 失败率
  
  setTimeout(() => {
    if (shouldFail) {
      return res.status(500).json({ error: '节点暂时不可用' });
    }
    
    res.set('Content-Type', 'application/octet-stream');
    res.send(fileData.shards[shardIndex]);
  }, delay);
});

// 列出可用文件
app.get('/files', (req, res) => {
  const files = Array.from(mockFiles.keys()).map(filename => {
    const data = mockFiles.get(filename);
    return {
      filename,
      size: data.totalSize,
      shards: data.shardCount
    };
  });
  
  res.json(files);
});

app.listen(PORT, () => {
  console.log(`Mock P2P 节点服务器运行在 http://localhost:${PORT}`);
  console.log('可用文件:', Array.from(mockFiles.keys()));
  console.log('\n示例下载链接:');
  console.log(`p2p://example.zip?peers=http://localhost:${PORT},http://localhost:${parseInt(PORT)+1},http://localhost:${parseInt(PORT)+2}&shards=100&rs=80,20`);
});


